import React from 'react';
import { Form, Input, Button, Select, DatePicker } from 'antd';
const { RangePicker } = DatePicker;
import './index.less'

const { Option } = Select;
// 判断是不是moment对象
const isMoment = (item) => item['_isAMomentObject'] ? item.format('YYYY-MM-DD') : item
// 表单类型
const types = {
    input: ({ placeholder }) => <Input style={{ width: 200 }} allowClear placeholder={placeholder || '请输入'} />,
    select: ({ placeholder, list }) => {
        return (
            <Select allowClear showSearch style={{ width: 200 }} placeholder={placeholder || '请选择'} filterOption>
                { list.map((sub, i) => <Option key={i} value={sub.value}>{sub.name}</Option>) }
            </Select>
        )
    },
    datePicker: ({ placeholder }) => <DatePicker style={{ width: 200 }} allowClear format="YYYY-MM-DD" placeholder={placeholder || '请选择'} />,
    rangePicker: ({ placeholder }) => <RangePicker allowClear format="YYYY-MM-DD" placeholder={placeholder || ['开始日期', '结束日期']} />,
}
class Header extends React.Component {
    formRef = React.createRef();
    onFinish = (values) => {
        // 提交表单之前判断是否有日期类型，如果有，须转成相应格式
        let temp = {}
        this.props.searchList.forEach(({ type, key }) => {
            if (type === 'datePicker' || type === 'rangePicker') {
                temp[key] = true
            }
        })
        for (const key in values) {
            values[key] = values[key] || ''
            if (values[key] && Object.keys(temp).length) {
                for (const k in temp) {
                    if (k === key) {
                        values[key] = Array.isArray(values[key]) ? values[key].map(item => isMoment(item)) : isMoment(values[key])
                    }
                }
            }
        }
        this.props.getSearchValues(values)
    };
    onReset = () => {
        this.formRef.current.resetFields();
    };
    render() {
        const { searchList } = this.props
        return (
            <Form className="my-header" ref={this.formRef} layout="inline" onFinish={this.onFinish}>
                {
                    searchList.map((item, index) => {
                        return (
                            <div key={index} className="my-form-item">
                                <Form.Item label={item.label} name={item.key}>
                                    { types[item.type](item) }
                                </Form.Item>
                            </div>
                        )
                    })
                }
                <Form.Item className="my-form-item">
                    <Button type="primary" htmlType="submit">查询</Button>
                    <Button className="right-btn" onClick={this.onReset}>重置</Button>
                </Form.Item>
            </Form>
        );
    }
}

export default Header
